package com.ktjy.test1;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author:雷淑娥
 * @Date:2024/12/11 17:03
 * version:1.0
 */
public class LoggingInvocationHandler implements MethodInterceptor {
//    private final Object target;
//
//    public LoggingInvocationHandler(Object target) {
//        this.target = target;
//    }
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        //获取实现类中的方法信息
        Method methodTarget = proxy.getClass().getMethod(method.getName());
        //判断方法上面是否有Log注解
        if (methodTarget.isAnnotationPresent(Log.class)) {
            String methodName = method.getName();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            LocalDateTime startTime = LocalDateTime.now();

            System.out.println("[LOG] Method:" + methodName + " started at:" + startTime.format(formatter));

            Object result = method.invoke(proxy,args);
            LocalDateTime endTime = LocalDateTime.now();
            long duration = java.time.Duration.between(startTime,endTime).toMillis();

            System.out.println("[LOG] Method:" + methodName + " ended at:" + endTime.format(formatter));
            System.out.println("[LOG] Method:" + methodName + " executed in:" + duration + "ms");
            return result;
        }else {
            return method.invoke(proxy,args);
        }
    }
}
